package repository

import (
	"gin-shop-admin/dao"
	"gin-shop-admin/models"
)

func GetAllProducts() (products []*models.Product, err error) {
	if err = dao.DB.Find(&products).Error; err != nil {
		return nil, err
	}
	return
}

func GetProducts(page int, limit int)(total int, product []*models.Product, err error)  {
	if err = dao.DB.Table("products").Count(&total).Error; err!=nil{
		return 0,nil,err
	}
	if err = dao.DB.Limit(limit).Offset((page-1)*limit).Find(&product).Error;err!=nil{
		return total,nil, err
	}
	return
}

func GetProductByID(id string) (product *models.Product, err error) {
	product = new(models.Product)
	if err := dao.DB.Where("id=?", id).First(&product).Error; err != nil {
		return nil, err
	}
	return
}

func InsertOneProduct(product *models.Product) error {
	return dao.DB.Create(&product).Error
}

func UpdateOneProduct(product *models.Product) (error) {
	return dao.DB.Save(product).Error
}

func DeleteProductByID(id string) (error) {
	return dao.DB.Where("id=?", id).Delete(&models.Product{}).Error
}
